package servlet;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.imgscalr.Scalr;
import org.json.JSONArray;
import org.json.JSONObject;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.imgscalr.Scalr.Mode;
import org.json.JSONException;
import service.Audio;
import service.Photo;
import service.PhotoCollection;
import service.PhotoCollectionFacadeREST;
import service.PhotoFacadeREST;
import service.Planet;
import service.PlanetFacadeREST;
import service.Tag;
import service.Video;
import session.UserData;

@Singleton
public class UploadServlet extends HttpServlet {

    private static final int IMG_WIDTH = 960;
    private static final int IMG_HEIGHT = 640;
    @EJB
    private PlanetFacadeREST planetManager;
    @EJB
    private PhotoFacadeREST photoManager;
    @EJB
    private PhotoCollectionFacadeREST photoCollectionManager;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     *
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //HttpSession session = request.getSession();
        HttpSession session = request.getSession();// don't create if it doesn't exist


        Integer universe_id = (Integer) session.getAttribute("idUniverse");
        Integer planet_id = (Integer) session.getAttribute("idPlanet");


        Integer happiness_session = Integer.parseInt(request.getParameter("happiness"));
        System.out.println("$$$Upload Servlet GET settato happiness a: " + happiness_session);
        boolean happiness;
        if (happiness_session == 1) {
            happiness = true;
        } else {
            happiness = false;
        }

        System.out.print("Numero universo preso: " + universe_id);
        System.out.print("Numero pianeta preso: " + planet_id);

        System.out.print("Getthumb not null: " + request.getParameter("getthumb"));


        if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
            System.out.println("Dentro getFile: " + request.getParameter("getfile"));
            File file = new File(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/image/" + request.getParameter("getfile"));
            if (file.exists()) {
                int bytes = 0;
                ServletOutputStream op = response.getOutputStream();

                response.setContentType(getMimeType(file));
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

                File f = new File(request.getServletContext().getRealPath("/") + File.separator + "Universes/" + universe_id + "/image/");
                //System.out.print("prrr000");
                byte[] bbuf = new byte[1024];
                DataInputStream in = new DataInputStream(new FileInputStream(file));

                while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                    op.write(bbuf, 0, bytes);
                }

                in.close();
                op.flush();
                op.close();

            }
        } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
//            System.out.print("v2");
            File file = new File(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/image/" + request.getParameter("delfile"));
            if (file.exists()) {
                file.delete(); // cancellazione file

                System.out.println("DA SCANCELLARE: " + request.getParameter("delfile"));

                // cancellazione record photo in db
                // prendo ultimo file inserito
                //  prendo pianeta con id = planet_id
                Planet currentPlanet = planetManager.find(planet_id);

                String tmpTitle;

                int idPhotoToDelete = -1;
                Photo photoToDel = new Photo();
                PhotoCollection newPhotoColl = new PhotoCollection();

                // prendere la photocollection associata 
                Collection<PhotoCollection> collPhoto = currentPlanet.getPhotoCollectionCollection();
                Iterator iterator = collPhoto.iterator();
                while (iterator.hasNext()) {
                    PhotoCollection p = (PhotoCollection) iterator.next();
                    if (p.getPlanetidPlanet().getIdPlanet() == planet_id) {

                        Collection<Photo> cf = p.getPhotoCollection();
                        Iterator iterator2 = cf.iterator();
                        while (iterator2.hasNext()) {
                            Photo photo = (Photo) iterator2.next();
                            tmpTitle = photo.getTitle() + ".jpg";
                            if (tmpTitle.equals(request.getParameter("delfile"))) {
                                photoToDel = photo;
                                System.out.println("DA SCANCELLARE id: " + photoToDel.getIdPhoto());
                                photoManager.remove(photoToDel);
                                iterator2.remove();
                            }
                        }

                        p.setPhotoCollection(cf);
                        photoCollectionManager.edit(p);


                    }
                }

            }
            // cancellazione immagine thumbs
            String pathThumbs = request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/image/" + request.getParameter("delfile").substring(0, request.getParameter("delfile").lastIndexOf(".")) + ".jpg";
            System.out.println("DA SCANCELLARE thumb: " + pathThumbs);
            File fileThumbs = new File(pathThumbs);
            if (fileThumbs.exists()) {
                fileThumbs.delete();
            }

        } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
            System.out.println("SONO IN GESTIONE GETTHUMB");
            File file = new File(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/image/" + request.getParameter("getthumb"));
            if (file.exists()) {
                //System.out.println(request.getParameter("getthumb")+"UGUALE?? "+photo.getTitle()+"_thumb.jpg");
                String mimetype = getMimeType(file);
                System.out.println("Quale mime? " + mimetype);
                //if(request.getParameter("getthumb").equals(photo.getTitle()+"_thumb.jpg")){
                //System.out.println("UGUALE");
                if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg") || mimetype.endsWith("gif")) {
                    System.out.println("DENTRO IF");
                    BufferedImage im = ImageIO.read(file);
                    if (im != null) {
                        BufferedImage thumb = Scalr.resize(im, 75);
                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        if (mimetype.endsWith("png")) {
                            ImageIO.write(thumb, "PNG", os);
                            response.setContentType("image/png");
                        } else if (mimetype.endsWith("jpeg")) {
                            ImageIO.write(thumb, "jpg", os);
                            response.setContentType("image/jpeg");
                        } else if (mimetype.endsWith("jpg")) {
                            ImageIO.write(thumb, "jpg", os);
                            response.setContentType("image/jpeg");
                        } else {
                            ImageIO.write(thumb, "GIF", os);
                            response.setContentType("image/gif");
                        }
                        ServletOutputStream srvos = response.getOutputStream();
                        response.setContentLength(os.size());
                        response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                        //renameFile(file.getName(), "i"+universe_id+"1"+".jpg");

                        os.writeTo(srvos);
                        srvos.flush();
                        srvos.close();
                    }
                }
                // }
            }

        } else {

            // lista di file già presenti sul server
            response.setContentType("application/json");
            File dir = new File(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/image/");
            String[] files = dir.list();
            JSONArray json = new JSONArray();

            Planet currentPlanet = planetManager.find(planet_id);
            // prendere la photocollection associata 
            Collection<PhotoCollection> collPhoto = currentPlanet.getPhotoCollectionCollection();

            String pathThumb = "";

            Iterator iterator = collPhoto.iterator();
            while (iterator.hasNext()) {
                PhotoCollection p = (PhotoCollection) iterator.next();
                if (p.getPlanetidPlanet().getIdPlanet() == planet_id) {
                    System.out.println("Happiness = " + happiness);
                    System.out.println("p.getIsHappy = " + p.getIsHappy());
                    if (p.getIsHappy() == happiness) {
                        System.out.println("NEL CICLO");
                        Collection<Photo> cf = p.getPhotoCollection();

                        Iterator iterator2 = cf.iterator();
                        while (iterator2.hasNext()) {
                            Photo photo = (Photo) iterator2.next();


                            pathThumb = photo.getPathPhoto();
                            try {
                                JSONObject jsono = new JSONObject();
                                jsono.put("name", photo.getTitle() + ".jpg");
                                //jsono.put("size", item.getSize());
                                jsono.put("url", "UploadServlet?happiness=" + happiness_session + "&getfile=" + photo.getTitle() + ".jpg");
                                jsono.put("thumbnail_url", "UploadServlet?happiness=" + happiness_session + "&getthumb=" + photo.getTitle() + ".jpg");
                                jsono.put("delete_url", "UploadServlet?happiness=" + happiness_session + "&delfile=" + photo.getTitle() + ".jpg");
                                jsono.put("delete_type", "GET");
                                json.put(jsono);

                            } catch (JSONException ex) {
                                Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                            }

                        }
                    }
                }
            }

            response.getWriter().write(json.toString());

        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     *
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist


        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());




        // ottieni id Universo
        Integer universe_id = (Integer) session.getAttribute("idUniverse");
        Integer planet_id = (Integer) session.getAttribute("idPlanet");


        //  prendo pianeta con id = planet_id
        Planet currentPlanet = planetManager.find(planet_id);

        // prendere la photocollection associata 
        Collection<PhotoCollection> collPhoto = currentPlanet.getPhotoCollectionCollection();
        System.out.println("Dim collPhoto = " + collPhoto.size());
        if (collPhoto.isEmpty()) {
            // Vettore vuoto
            System.out.println("Foto collection QUI");
            // creo collezione Happy
            PhotoCollection collHappy = new PhotoCollection();

            collHappy.setPlanetidPlanet(currentPlanet);
            collHappy.setDescription(" ");
            collHappy.setIsHappy(true);
            // inserimento in db
            //photoCollectionManager.edit(collHappy);

            PhotoCollection collSad = new PhotoCollection();
            collSad.setPlanetidPlanet(currentPlanet);
            collSad.setDescription(" ");
            collSad.setIsHappy(false);
            // inserimento in db
            //photoCollectionManager.edit(collSad);

            collPhoto.add(collHappy);
            collPhoto.add(collSad);

            currentPlanet.setPhotoCollectionCollection(collPhoto);

            // aggiorno in database
            planetManager.edit(currentPlanet);


        }


        PrintWriter writer = response.getWriter();
        response.setContentType("application/json");
        JSONArray json = new JSONArray();





        try {

            Map<String, String> otherParameters = new HashMap<String, String>();

            List<FileItem> items;
            items = uploadHandler.parseRequest(request);

            Integer happiness_session = null;
            // secure
            for (FileItem item : items) {
                if (item.isFormField() && item.getFieldName().equals("happiness")) {
                    happiness_session = Integer.parseInt(item.getString());

                    System.out.println("$$$Upload Servlet POST settato " + item.getFieldName() + " a: " + happiness_session);
                    break;
                }
            }

            for (FileItem item : items) {


                if (!item.isFormField()) {
                    File file = new File(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/image/", item.getName());
                    item.write(file);
                    String mimetype = getMimeType(file);

                    if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg") || mimetype.endsWith("gif")) {
                        // imagine supportata
                        BufferedImage im = ImageIO.read(file);
                        System.out.println("W: " + im.getWidth() + " && H: " + im.getHeight());

                        if ((im.getWidth() >= 960) && (im.getHeight() >= 640)) {

                            // si può effettivamente caricare l'immagine




                            // setto il numero della nuova foto
                            Collection<Photo> cp = photoManager.findAll();
                            Iterator<Photo> photoIt = cp.iterator();
                            Photo photo = null;

                            int currentIDphoto = -1;

                            while (photoIt.hasNext()) {
                                photo = photoIt.next();
                                if (photo.getIdPhoto() > currentIDphoto) {
                                    currentIDphoto = photo.getIdPhoto();
                                }
                            }

                            //incremento contatore di uno per assegnare l'indice al file da inserire
                            currentIDphoto++;

                            currentPlanet = planetManager.find(planet_id);
                            //            
                            if (happiness_session == 1) {
                                //              // sono su collection Happy
                                System.out.println("Parte Happy");

                                Collection<PhotoCollection> coll = currentPlanet.getPhotoCollectionCollection();
                                //                
                                Iterator iterator = coll.iterator();
                                while (iterator.hasNext()) {
                                    PhotoCollection p = (PhotoCollection) iterator.next();
                                    if (p.getPlanetidPlanet().getIdPlanet() == planet_id) {
                                        //                        
                                        if (p.getIsHappy()) {

                                            String pathAndNamePhoto = universe_id + "/image/" + "i" + universe_id + currentIDphoto + ".jpg";

                                            // inserisco nuova foto
                                            Collection<Photo> photoList = p.getPhotoCollection();
                                            Photo newPhoto = new Photo();
                                            newPhoto.setIsHappy(true);
                                            newPhoto.setPathPhoto(pathAndNamePhoto);

                                            newPhoto.setPhotoCollectionidPhotoCollection(p);

                                            newPhoto.setTitle("i" + universe_id + currentIDphoto);

                                            photoList.add(newPhoto);

                                            //System.out.println("valore idd= "+p.getIdPhotoCollection());

                                            PhotoCollection fc = p;//photoCollectionManager.find(p);

                                            fc.setPhotoCollection(photoList);

                                            photoCollectionManager.edit(fc);
                                            break;
                                        }

                                    }
                                }

                            } else {
                                // sono su collection Sad
                                Collection<PhotoCollection> coll = currentPlanet.getPhotoCollectionCollection();

                                System.out.println("Parte Sad");

                                Iterator iterator = coll.iterator();
                                while (iterator.hasNext()) {
                                    PhotoCollection p = (PhotoCollection) iterator.next();
                                    if (p.getPlanetidPlanet().getIdPlanet() == planet_id) {

                                        if (p.getIsHappy() == false) {

                                            String pathAndNamePhoto = universe_id + "/image/" + "i" + universe_id + currentIDphoto + ".jpg";

                                            // inserisco nuova foto
                                            Collection<Photo> photoList = p.getPhotoCollection();
                                            Photo newPhoto = new Photo();
                                            newPhoto.setIsHappy(false);
                                            newPhoto.setPathPhoto(pathAndNamePhoto);

                                            newPhoto.setPhotoCollectionidPhotoCollection(p);

                                            newPhoto.setTitle("i" + universe_id + currentIDphoto);

                                            photoList.add(newPhoto);

                                            PhotoCollection fc = p;//photoCollectionManager.find(p);

                                            fc.setPhotoCollection(photoList);

                                            photoCollectionManager.edit(fc);
                                            break;
                                        }

                                    }
                                }
                            }

                            JSONObject jsono = new JSONObject();
                            jsono.put("name", "i" + universe_id + currentIDphoto + ".jpg");
                            //jsono.put("size", item.getSize());
                            jsono.put("url", "UploadServlet?happiness=" + happiness_session + "&getfile=" + "i" + universe_id + currentIDphoto + ".jpg");
                            jsono.put("thumbnail_url", "UploadServlet?happiness=" + happiness_session + "&getthumb=" + "i" + universe_id + currentIDphoto + ".jpg");
                            jsono.put("delete_url", "UploadServlet?happiness=" + happiness_session + "&delfile=" + "i" + universe_id + currentIDphoto + ".jpg");
                            jsono.put("delete_type", "GET");

                            json.put(jsono);
                            //                            System.out.println(json.toString());
                            //
                            resizeImage(request.getServletContext().getRealPath("/") + "Universes/" + universe_id + "/image/" + item.getName(), "i" + universe_id + currentIDphoto);


                        } else {
                            System.out.println("Immagine troppo piccola per essere caricata");
                            JSONObject jsonerror = new JSONObject();

                            String htmlResponse = "<p class=\"text-center\">\n"
                                    + "                                <span style=\"font-size: 14px; text-decoration: underline;\">Non &egrave; stato possibile caricare il file:</span> <br /> <strong>l'immagine &egrave; troppo piccola per essere caricata.</strong>\n"
                                    + "                            </p>\n"
                                    + "                            <p>Controlla le caratteristiche necessarie per il caricamento in MuMu, in particolare:\n"
                                    + "                            <ul>\n"
                                    + "                                <li>Le immagini da caricare devono avere dimensioni minime di <strong>960 X 640 pixel</strong></li>\n"
                                    + "                            </ul>\n"
                                    + "                            </p>";

                            jsonerror.put("error", htmlResponse);
//                            jsonerror.put("error", "L'immagine troppo piccola per essere caricata");
                            json.put(jsonerror);
                            deleteFile(file);
                        }


                    } else {
                        // immagine non supportata
                        System.out.println("Formato immagine non supportato");
                        JSONObject jsonerror = new JSONObject();

                        String htmlResponse = "<p class=\"text-center\">\n"
                            + "                                <span style=\"font-size: 14px; text-decoration: underline;\">Non &egrave; stato possibile caricare il file:</span> <br /> <strong>il formato dell'immagine non &egrave; supportato.</strong>\n"
                                + "                            </p>\n"
                                + "                            <p>Controlla le caratteristiche necessarie per il caricamento in MuMu, in particolare:\n"
                                + "                            <ul>\n"
                                + "                                <li>Le immagini da caricare devono essere in formato <strong>JPEG, PNG o GIF</strong></li>\n"
                                + "                            </ul>\n"
                                + "                            </p>";

                        jsonerror.put("error", htmlResponse);
//                        jsonerror.put("error", "Formato immagine non supportato");
                        json.put(jsonerror);
                        // cancellazione file
                        deleteFile(file);
                    }


                }
//                    else {
//                        otherParameters.put(item.getFieldName(), item.getString());
//                        System.out.println("$$$$$$$ Nome"+item.getFieldName()+" valore: "+item.getString());
//                    }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            writer.write(json.toString());
            System.out.println("Stringa in JSON: " + json.toString());
            writer.close();
        }

    }

    private String getMimeType(File file) {
        String mimetype = "";
        if (file.exists()) {
            if (getSuffix(file.getName()).equalsIgnoreCase("png")) {
                mimetype = "image/png";
            } else if (getSuffix(file.getName()).equalsIgnoreCase("jpg")) {
                mimetype = "image/jpg";
            } else if (getSuffix(file.getName()).equalsIgnoreCase("jpeg")) {
                mimetype = "image/jpeg";
            } else if (getSuffix(file.getName()).equalsIgnoreCase("gif")) {
                mimetype = "image/gif";
            } else {
                javax.activation.MimetypesFileTypeMap mtMap = new javax.activation.MimetypesFileTypeMap();
                mimetype = mtMap.getContentType(file);
            }
        }
        return mimetype;
    }

    private void resizeImage(String fullPath, String newName) throws IOException {
        File file = new File(fullPath);
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg") || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {

                    BufferedImage thumb;

                    if (mimetype.endsWith("png")) {
                        BufferedImage bi = Scalr.resize(im, Mode.AUTOMATIC, 960, 640);
                        if (bi.getWidth() < 960) {
                            bi = Scalr.rotate(im, Scalr.Rotation.CW_270);
                            bi = Scalr.resize(bi, Mode.AUTOMATIC, 960, 640);
                        }
                        
                        if (bi.getHeight() < 640) {
                            bi = Scalr.resize(im, Mode.FIT_TO_HEIGHT, 960, 640);
                        }

                        im = Scalr.crop(bi, 960, 640);

                        thumb = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_RGB);
                        thumb.createGraphics().drawImage(im, 0, 0, Color.WHITE, null);

                        // write to jpeg file
                        //ImageIO.write(thumb, "jpg", new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName + "_thumb" + "." + "jpg"));
                        ImageIO.write(thumb, "jpg", new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName + "." + "jpg"));

                        try {
                            if (file.delete()) {
                                System.out.println(file.getName() + " is deleted!");
                            } else {
                                System.out.println("Delete operation is failed.");
                            }

                        } catch (Exception e) {
                        }

                    } else if ((mimetype.endsWith("jpeg")) || (mimetype.endsWith("jpg"))) {


                        BufferedImage bi = Scalr.resize(im, Mode.AUTOMATIC, 960, 640);
                        if (bi.getWidth() < 960) {
                            bi = Scalr.rotate(im, Scalr.Rotation.CW_270);
                            bi = Scalr.resize(bi, Mode.AUTOMATIC, 960, 640);
                        }
                        if (bi.getHeight() < 640) {
                            bi = Scalr.resize(im, Mode.FIT_TO_HEIGHT, 960, 640);
                        }

                        System.out.println("bi.getWidth = " + bi.getWidth());
                        System.out.println("bi.getHeight = " + bi.getHeight());
                        im = Scalr.crop(bi, 960, 640);

                        // write to jpeg file
                        //ImageIO.write(im, "jpg", new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName + "_thumb" + "." + "jpg"));
                        ImageIO.write(im, "jpg", new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName + "." + "jpg"));

                        try {
                            if (file.delete()) {
                                System.out.println(file.getName() + " cancellato!");
                            } else {
                                System.out.println("Operazione di cancellazione fallita.");
                            }

                        } catch (Exception e) {
                        }

                    } else if (mimetype.endsWith("gif")) {
                        BufferedImage bi = Scalr.resize(im, Mode.AUTOMATIC, 960, 640);
                        if (bi.getWidth() < 960) {
                            bi = Scalr.rotate(im, Scalr.Rotation.CW_270);
                            bi = Scalr.resize(bi, Mode.AUTOMATIC, 960, 640);
                        }
                        
                        if (bi.getHeight() < 640) {
                            bi = Scalr.resize(im, Mode.FIT_TO_HEIGHT, 960, 640);
                        }
                        
                        im = Scalr.crop(bi, 960, 640);

                        thumb = new BufferedImage(im.getWidth(), im.getHeight(), BufferedImage.TYPE_INT_RGB);
                        thumb.createGraphics().drawImage(im, 0, 0, Color.WHITE, null);

                        // write to jpeg file
                        //ImageIO.write(thumb, "jpg", new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName + "_thumb" + "." + "jpg"));
                        ImageIO.write(thumb, "jpg", new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/") + 1) + newName + "." + "jpg"));

                        try {
                            if (file.delete()) {
                                System.out.println(file.getName() + " is deleted!");
                            } else {
                                System.out.println("Delete operation is failed.");
                            }

                        } catch (Exception e) {
                        }

                    }

                    if (!file.exists() || file.isDirectory()) {

                        System.out.println("File does not exist: " + file);
                        return;
                    }
                }
            }
        }
    }

    public void renameFile(String file, String toFile) {

        File toBeRenamed = new File(file);

        if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {

            System.out.println("File does not exist: " + file);
            return;
        }

        File newFile = new File(toFile);

        //Rename
        if (toBeRenamed.renameTo(newFile)) {
            System.out.println("File has been renamed.");
        } else {
            System.out.println("Error renmaing file");
        }


    }

    private static void deleteFile(File filePassed) {
        try {

            if (filePassed.delete()) {
                System.out.println(filePassed.getName() + " is deleted!");
            } else {
                System.out.println("Delete operation is failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getSuffix(String filename) {
        String suffix = "";
        int pos = filename.lastIndexOf('.');
        if (pos > 0 && pos < filename.length() - 1) {
            suffix = filename.substring(pos + 1);
        }
        return suffix;
    }
}
